package com.hnkywl.sts.service.kcgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.jsgl.ZjbcdDao;
import com.hnkywl.sts.dao.jsgl.ZjbcdRzDao;
import com.hnkywl.sts.dao.kcgl.KcgdDao;
import com.hnkywl.sts.dao.xsgl.GdDao;
import com.hnkywl.sts.dao.xsgl.KhDao;
import com.hnkywl.sts.dao.xsgl.ShjDao;
import com.hnkywl.sts.entity.base.Sjzdz;
import com.hnkywl.sts.entity.cggl.Cgd;
import com.hnkywl.sts.entity.cggl.Zjbcd;
import com.hnkywl.sts.entity.cggl.ZjbcdRz;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.xsgl.Gd;
import com.hnkywl.sts.entity.xsgl.Kh;
import com.hnkywl.sts.service.base.WebserviceTransService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.service.xsgl.XsdService;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-4-30
 * Time: 上午11:32
 * To change this template use File | Settings | File Templates.
 */
@Service
public class KcgdService {
    private KcgdDao kcgdDao;
    private ZjbcdDao zjbcdDao;
    private ZjbcdRzDao zjbcdRzDao;
    private XsdService xsdService;
    private CgdDao cgdDao;
    private ShjDao shjDao;
    private GdDao gdDao;
    private KhDao khDao;
    private final static int COUNT_OUT = 10;
    private final static int TIME_OUT = 10000;
    private WebserviceTransService webserviceTransService;

    //实时库存查询列表
    public String findList(String gdwyh, String clh, String bh, String cpm, String pm, String cz, String ggxh, String zyzt, String kcgdstart, String kcgdend, int pageNo, int pageSize) {
        Page<Gd> page = kcgdDao.findList(gdwyh, clh, bh, cpm, pm, cz, ggxh, zyzt, kcgdstart, kcgdend, pageNo, pageSize);
        List<Gd> gdList = page.getResult() == null ? new ArrayList<Gd>() : page.getResult();
        String gdJson = BaseUtils.fetchCollectionToJson(gdList, "id", "layerDefect", "dateCreated", "resource_serial_number", "matNo", "factoryId", "packageId", "pc", "apn", "prodDesc", "cate", "material", "spec", "brand", "warehouse", "measureCount", "measure", "price", "productionDate", "standard", "zyzt");
        List<Map> sumList = kcgdDao.findSumKh(gdwyh, clh, bh, cpm, pm, cz, ggxh, zyzt, kcgdstart, kcgdend);
        Double zzl = 0d;
        if (null != sumList && sumList.size() != 0) {
            for (Map map : sumList) {
                zzl += Double.valueOf((map.get("zzl") == null ? 0d : map.get("zzl")).toString());
            }
            return "{\"total\":" + page.getTotalCount() + ",\"rows\":[" + gdJson + "],\"footer\":[{\"dateCreated\":\"合计:\",\"measure\":" + zzl + " }]}";
        } else {
            return "{\"total\":" + page.getTotalCount() + ",\"rows\":[" + gdJson + "]}";
        }

    }

    //################################挂单方法#############################################

    //根据卡号IDs找到卡号集合
    public String findWzMxFromKhIDs(String khIds) {
        String[] khStr = khIds.split(",");
        List<Long> khIdList = new ArrayList<Long>();
        for (int i = 0; i < khStr.length; i++) {
            khIdList.add(Long.parseLong(khStr[i]));
        }
        Gson gson = new Gson();
        List<Map> khlist = this.kcgdDao.findKcgdGdWzmxFromKhIds(khIdList);
        for (int i = 0; i < khlist.size(); i++) {
            for (int j = 0; j < khIdList.size(); j++) {
                if (((Long) khlist.get(i).get("id")).longValue() == khIdList.get(j).longValue()) {
                    Map<String, Object> rs = shjDao.calculate(khIdList.get(j));
                    khlist.get(i).put("shj", rs.get("hsj"));
                    khlist.get(i).put("lxjt", rs.get("yhjg"));
                    khlist.get(i).put("jsfs", rs.get("jsfs"));
                }
            }
        }
        String result = "{\"rows\":" + gson.toJson(khlist) + "}";
        return result;
    }

    //挂单方法
    @Transactional
    public synchronized String gd(List<Kh> khList) throws Exception {
//        List<Kh> khs = new ArrayList<Kh>();
//        for (Kh kh : khList) {
//            Kh newKh = kcgdDao.get(kh.getId());
//            if (newKh.getKkdsl() < kh.getGdsl()) {
//                throw new RuntimeException(newKh.getKhbm() + "该卡号的可开单数量不足挂单数量请重新选择!");
//            }
//            newKh.setLssl(kh.getGdsl());
//            newKh.setLsjs(kh.getGdjs());
//            newKh.setGdjs(0);
//            newKh.setGdsl(0d);
//            Double jz = (Math.round((newKh.getLssl() / newKh.getLsjs()) * 1000000) / 1000000.0);
//            newKh.setJz(jz);
//            newKh.setKhdj(kh.getKhdj());
//            khs.add(newKh);
//        }
//        String json = xsdService.createJsonToInterFace(null, khs);
//
//        String result = webserviceTransService.transGdWebServiceArgs(khs.get(0).getCggs().getBm(), json);
//        Gson gson = new Gson();
//
//        List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
//        try {
//            map = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>() {
//            }.getType());
//        } catch (Exception e) {
//            Map<String, Object> value = gson.fromJson(result, new TypeToken<Map<String, Object>>() {
//            }.getType());
//            map.add(value);
//        }
//
//
//        String Failures = "";
//        if (map == null || map.size() == 0) {
//            throw new RuntimeException("挂单接口返回为空,请与交易系统核实!");
//        } else {
//            for (int i = 0; i < map.size(); i++) {
//                if ("0".equals(map.get(i).get("code").toString())) {
//                    if (map.get(i).get("resource_serial_number") != null) {
//                        Gd gd = gdDao.findGdByCode(map.get(i).get("resource_serial_number").toString());
//                        if (gd != null && gd.getId() != null) {
//                            if (map.get(i).get("hangcode") != null) {
//                                this.gdChangeKhKkdslSec(khs, map.get(i).get("resource_serial_number").toString());
//                                gd.setHangcode(map.get(i).get("hangcode").toString());
//                                this.savaGd(gd);
//                            } else {
//                                Failures = "传入的交易系统挂牌号为空";
//                            }
//                        } else {
//                            Failures = "根据" + map.get(i).get("resource_serial_number").toString() + "未找到挂单单据";
//                        }
//                    } else {
//                        Failures = "传入的挂单资源唯一号为空";
//                    }
//                } else {
//                    if (map.get(i).get("resource_serial_number") != null)
//                        Failures += this.analyzeMapCgdh(map.get(i).get("resource_serial_number").toString());
//                    else
//                        Failures = map.get(i).get("message").toString();
//                }
//            }
//            if ("".equals(Failures)) {
//                Failures = "挂单成功";
//            }
//        }
        return "Failures";
    }


    public String analyzeMapCgdh(String str) {
        String[] strings = str.split("-");
        return strings[0] + "-" + strings[1] + "第" + strings[2] + "物资挂单失败;";
    }

    @Transactional
    public synchronized void gdChangeKhKkdslSec(List<Kh> khs, String str) {
//        String[] strings = str.split("-");
//        Cgd cgd = cgdDao.findCgdFindCgdh(strings[0] + "-" + strings[1]);
//        List<Kh> khList = cgd.getKhList();
//        for (Kh kh : khList) {
//            if (kh.getPxh() == Integer.parseInt(strings[2])) {
//                for (Kh k : khs) {
//                    if (k.getId() == kh.getId()) {
//                        kh.setGdsl(k.getLssl());
//                        kh.setGdjs(k.getLsjs());
//                        kh.setGdslhj(kh.getGdslhj() == null ? kh.getGdsl() : kh.getGdslhj() + kh.getGdsl());
//                        kh.setGdjshj(kh.getGdjshj() == null ? kh.getGdjs() : kh.getGdjshj() + kh.getGdjs());
//                        Double jz = (Math.round((kh.getGdsl() / kh.getGdjs()) * 1000000) / 1000000.0);
//                        kh.setJz(jz);
//                        kh.setKhdj(k.getKhdj());
//                        kh.setKkdsl(kh.getKkdsl() - kh.getGdsl());
//                        kcgdDao.save(kh);
//                    }
//                }
//            }
//        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void savaGd(Gd gd) {
        gdDao.save(gd);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void changeKhFormGd(Gd gd, List<Kh> regionKh) {
        //   Kh nKh = gd.getKh();
        Kh nKh = null;
        if (nKh != null && nKh.getId() != null) {
            for (Kh k : regionKh) {
                if (nKh.getId() == k.getId()) {
                    nKh.setGdsl(k.getLssl());
                    nKh.setGdjs(k.getLsjs());
                    nKh.setGdslhj(nKh.getGdslhj() == null ? nKh.getGdsl() : nKh.getGdslhj() + nKh.getGdsl());
                    nKh.setGdjshj(nKh.getGdjshj() == null ? nKh.getGdjs() : nKh.getGdjshj() + nKh.getGdjs());
                    nKh.setKhdj(nKh.getKhdj());
                    nKh.setJz(k.getJz());
                    nKh.setKkdsl(0d);
                    khDao.save(nKh);
                }
            }
        } else {
            String[] strings = gd.getResource_serial_number().split("-");
            Cgd cgd = cgdDao.findCgdFindCgdh(strings[0] + "-" + strings[1]);
            List<Kh> khList = cgd.getKhList();
            for (Kh nkh : khList) {
                if (nkh.getPxh() == Integer.parseInt(strings[2])) {
                    for (Kh k : regionKh) {
                        if (nKh.getId() == k.getId()) {
                            nKh.setGdsl(k.getLssl());
                            nKh.setGdjs(k.getLsjs());
                            nKh.setGdslhj(nKh.getGdslhj() == null ? nKh.getGdsl() : nKh.getGdslhj() + nKh.getGdsl());
                            nKh.setGdjshj(nKh.getGdjshj() == null ? nKh.getGdjs() : nKh.getGdjshj() + nKh.getGdjs());
                            nKh.setKhdj(nKh.getKhdj());
                            nKh.setJz(k.getJz());
                            nKh.setKkdsl(0d);
                            khDao.save(nKh);
                        }
                    }
                }
            }
        }
    }
    //#############################################################################

    @Transactional
    public Kh findKhDetail(Long id) {
//        return this.kcgdDao.get(id);
        return null;
    }

    @Transactional
    public void changeStatus(Long id, String status) {
        Kh kh1 = this.findKhDetail(id);
        /*  Yg kpr = YgService.getCurrentYg();
       cgjsd.setKpr(kpr);
       cgjsd.setKprq(new Date());*/
//        kh1.setQk(status.equals("true"));
//        this.kcgdDao.save(kh1);
    }

    //实时库存明细
    @Transactional
    public Kh findKcgdDetail(Long id) {
//        return this.kcgdDao.get(id);
        return null;
    }

    /**
     * 库存成本调整
     *
     * @param kh
     */
    @Transactional
    public void kccbtz(Kh kh) {
//        Kh k = kcgdDao.get(kh.getId());
        Kh k = null;
        if (k.getQk()) {
            throw new RuntimeException("已清卡，不能进行调整！");
        }
        if (k.getWsdj().doubleValue() != kh.getWsdj().doubleValue()) {
            Zjbcd zjbcd = new Zjbcd();
            Sjzdz sjzdz = new Sjzdz();
            sjzdz.setId(50L);
            zjbcd.setLb(sjzdz);
            java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
            String slstr = df.format((kh.getWsdj() - k.getWsdj()) * kh.getSl());
            zjbcd.setJe(Double.parseDouble(slstr));
            zjbcd.setZt("ybc");
            if (kh.getGys() != null)
                zjbcd.setGys(kh.getGys());
            else {
                Gsjg gsjg = new Gsjg();
                gsjg.setId(-1l);
                zjbcd.setGys(gsjg);
            }
            zjbcd.setCreateUser(YgService.getCurrentYg());
            zjbcd.setDateCreated(new Date());
            zjbcd.setLastUpdated(zjbcd.getDateCreated());
            zjbcd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            zjbcd.setCreateOrgan(YgService.getCurrentYg().getZggs());
            zjbcd.setSftzsc(true);
            zjbcdDao.save(zjbcd);
            ZjbcdRz zjbcdRz = new ZjbcdRz();
            zjbcdRz.setKh(k);
            zjbcdRz.setZjbcd(zjbcd);
            zjbcdRz.setYkccb(k.getWsdj());
            zjbcdRz.setXkccb(kh.getWsdj());
            zjbcdRz.setCreateUser(YgService.getCurrentYg());
            zjbcdRz.setDateCreated(new Date());
            zjbcdRz.setLastUpdated(zjbcdRz.getDateCreated());
            zjbcdRz.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            zjbcdRz.setCreateOrgan(YgService.getCurrentYg().getZggs());
            zjbcdRzDao.save(zjbcdRz);
            k.setWsdj(kh.getWsdj());
            k.setLastUpdated(new Date());
//            kcgdDao.save(k);
        }
    }

    /**
     * 定时报送所有卡号到交易挂单
     *
     * @param khList
     * @throws Exception
     */
    @Transactional
    public synchronized void gdToOrderTime(String mark, List<Kh> khList) throws Exception {
//
//        int size = khList.size();
//        double model = Math.ceil((double) size / (double) COUNT_OUT);
//        for (int i = 0; i < model; i++) {
//            int region = size >= COUNT_OUT * (i + 1) ? COUNT_OUT * (i + 1) : size;
//            List<Kh> regionKh = new ArrayList<Kh>();
//            for (int j = i * COUNT_OUT; j < region; j++) {
//                Kh newKh = kcgdDao.get(khList.get(j).getId());
//                Double jz = (newKh.getJz() == null ? (Math.round((newKh.getKkdsl() / newKh.getJs()) * 1000000) / 1000000.0) : newKh.getJz());
//                newKh.setLssl(newKh.getKkdsl());
//                newKh.setLsjs(newKh.getJs());
//                newKh.setGdsl(0d);
//                newKh.setGdjs(0);
//                newKh.setJz(jz);
//                newKh.setKhdj(newKh.getKhdj());
//                regionKh.add(newKh);
//            }
//            String json = xsdService.createJsonToInterFace(mark, regionKh);
//
//            String result = webserviceTransService.transGdWebServiceArgs(regionKh.get(0).getCggs().getBm(), json);
//
//            Gson gson = new Gson();
//            List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
//            try {
//                map = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>() {
//                }.getType());
//            } catch (Exception e) {
//                Map<String, Object> value = gson.fromJson(result, new TypeToken<Map<String, Object>>() {
//                }.getType());
//                map.add(value);
//            }
//            if (map != null && map.size() != 0) {
//                for (Map<String, Object> aMap : map) {
//                    if ("0".equals(aMap.get("code").toString()) || "10".equals(aMap.get("code").toString())) {
//                        if (aMap.get("resource_serial_number") != null) {
//                            Gd gd = gdDao.findGdByCode(aMap.get("resource_serial_number").toString());
//                            if (gd != null && gd.getId() != null) {
//                                if (aMap.get("hangcode") != null) {
//                                    gd.setHangcode(aMap.get("hangcode").toString());
//                                    this.savaGd(gd);
//                                    this.changeKhFormGd(gd, regionKh);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//            Thread.sleep(TIME_OUT);   //延时10s后执行下一个循环
//        }
    }


    @Autowired
    public void setKcgdDao(KcgdDao kcgdDao) {
        this.kcgdDao = kcgdDao;
    }

    @Autowired
    public void setZjbcdDao(ZjbcdDao zjbcdDao) {
        this.zjbcdDao = zjbcdDao;
    }

    @Autowired
    public void setZjbcdRzDao(ZjbcdRzDao zjbcdRzDao) {
        this.zjbcdRzDao = zjbcdRzDao;
    }

    @Autowired
    public void setXsdService(XsdService xsdService) {
        this.xsdService = xsdService;
    }

    @Autowired
    public void setWebserviceTransService(WebserviceTransService webserviceTransService) {
        this.webserviceTransService = webserviceTransService;
    }

    @Autowired
    public void setCgdDao(CgdDao cgdDao) {
        this.cgdDao = cgdDao;
    }

    @Autowired
    public void setShjDao(ShjDao shjDao) {
        this.shjDao = shjDao;
    }

    @Autowired
    public void setGdDao(GdDao gdDao) {
        this.gdDao = gdDao;
    }

    @Autowired
    public void setKhDao(KhDao khDao) {
        this.khDao = khDao;
    }
}
